package com.leps.nq.common.excel;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.leps.nq.bu.entity.BuStation;
import com.leps.nq.bu.service.IBuStationService;
import com.leps.nq.common.util.SpringUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;

public class ExcelPageReadListener2<T extends ExcelImportVo> extends AnalysisEventListener<T> implements ReadListener<T> {
    private IBuStationService stationService = SpringUtils.getBean(IBuStationService.class);
    public static int BATCH_COUNT = 100;
    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final Consumer<List<T>> consumer;

    public ExcelPageReadListener2(Consumer<List<T>> consumer) {
        this.consumer = consumer;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException e = (ExcelDataConvertException) exception;
            Integer rowIndex = e.getRowIndex();
            Integer columnIndex = e.getColumnIndex();
            String data = e.getCellData().getStringValue();
            String msg = StrUtil.format("第{}行，第{}列解析异常，数据为:{}", rowIndex, columnIndex + 1, data);
            throw new RuntimeException(msg, e);
        }
        ReadListener.super.onException(exception, context);
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            this.checkStation(cachedDataList);
            consumer.accept(cachedDataList);
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (CollectionUtils.isNotEmpty(cachedDataList)) {
            this.checkStation(cachedDataList);
            consumer.accept(cachedDataList);
        }
    }

    public void checkStation(List<T> list) {
        Iterator<T> iterator = list.iterator();
        while (iterator.hasNext()) {
            T vo = iterator.next();
            final Integer serialNumber = vo.getSerialNumber();
            final String stationName = StrUtil.trim(vo.getStationName());
            // 如果平台名称为空，抛出异常
            if (ObjectUtil.isEmpty(stationName)) {
                String msg = StrUtil.format("序号为{}的数据行缺少归属场站", vo.getSerialNumber());
                throw new RuntimeException(msg);
            }
            // 根据平台名称查询区块id及归属区块、归属客户
            BuStation station =  this.stationService.lambdaQuery().eq(BuStation::getStationName, stationName).one();
            // 如果查不到对应平台，抛出异常
            if (station == null) {
                String msg = StrUtil.format("序号为{}的数据行归属场站错误：系统中不存在 [ {} ] 这个场站", vo.getSerialNumber(), vo.getStationName());
                throw new RuntimeException(msg);
            }
            // 填充数据
            vo.setStationId(station.getStationId());
            vo.setAreaId(station.getAreaId());
            vo.setAreaName(station.getAreaName());
            vo.setCustId(station.getCustId());
            vo.setCustName(station.getCustName());
        }
    }

}
